import {
  getOrderAddress,
  getOrderDetail,
  orderBuy,
  submitOrder,
  getWebchatOrder,
  getWebchatOrderStateSel
} from '../../../api/order'
import formatTime from '../../../utils/formatTime'
import Schema from 'async-validator'
import {
  toast
} from '@/utils/extendApi'
import {
  debounce
} from 'miniprogram-licia'
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    deliveryDate: '', // 期望送达日期
    blessing: '', // 祝福语
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    addressInfo: {},
    cartVoList: [],
    totalAmount: null
  },
  // 提交订单
  submitOrder: debounce(async function () {
    const {
      buyName,
      buyPhone,
      cartVoList,
      deliveryDate,
      blessing,
      addressInfo
    } = this.data
    // 准备提交订单的接口参数
    const params = {
      buyName,
      buyPhone,
      cartList: cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: addressInfo.id
    }
    const {
      validateRes
    } = await this.validatorOrderInfo(params)
    // 如果校验通过，则提交订单
    if (validateRes) {
      const res = await submitOrder(params)
      this.advanceOrder(res.data)
    }
  }, 500),
  // 获取微信预支付信息
  async advanceOrder(orderNo) {
    try {
      const result = await getWebchatOrder(orderNo)
      const payRes = await wx.requestPayment(result.data)
      if (payRes.errMsg === 'requestPayment:ok') {
        const stateRes = await getWebchatOrderStateSel(orderNo)
        if (stateRes.code === 200) {
          wx.redirectTo({
            url: '/pages/order/list/index',
            success: () => {
              toast({
                title: '支付成功',
                icon: 'success'
              })
            }
          })
        }
      }

    } catch (error) {
      toast({
        title: '支付失败',
        icon: 'error'
      })
    }

  },
  // 收货地址表单校验
  validatorOrderInfo(params) {
    // 验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    // 验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    // 校验规则
    const rules = {
      userAddressId: [{
        required: true,
        message: '请选择收货地址'
      }],
      buyName: [{
        require: true,
        message: '姓名不能为空'
      }, {
        pattern: nameRegExp,
        message: '姓名不合法'
      }],
      buyPhone: [{
        require: true,
        message: '手机号不能为空'
      }, {
        pattern: phoneReg,
        message: '订购人手机号不合法'
      }],
      remarks: [{
        require: true,
        message: '祝福语不能为空'
      }]
    }
    const validator = new Schema(rules)
    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          toast({
            title: errors[0].message,
            icon: 'error'
          })
          resolve({
            validateRes: false
          })
        } else {
          resolve({
            validateRes: true
          })
        }
      })
    })

  },
  onShow() {
    this.getOrderAddress()
    this.getOrderDetail()
  },
  // 获取订单地址
  async getOrderAddress() {
    const {
      data
    } = await getOrderAddress()
    this.setData({
      addressInfo: data
    })
  },
  //获取订单商品列表
  async getOrderDetail() {
    const {
      goodsId,
      blessing

    } = this.data
    let res
    if (goodsId) {
      //立即购买，进行的订单提交
      res = await orderBuy({
        goodsId,
        blessing
      })
    } else {
      //购物车页面进行的提交
      res = await getOrderDetail()
    }

    this.setData({
      cartVoList: res.data.cartVoList,
      totalAmount: res.data.totalAmount
    })
  },
  onLoad(options) {
    // 获取页面跳转参数
    this.setData({
      ...options
    })
  },
  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker({
    detail
  }) {
    // 调用日期格式化方法对时间戳进行处理
    const timeRes = formatTime(new Date(detail))
    this.setData({
      deliveryDate: timeRes
    })
    this.setData({
      show: false
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },

  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/address/list/index'
    })
  }
})